package com.song.boot.springstudy.ms.szjz.al3;

import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class Sha256Utils {

    /**
     * 计算字符串的 SHA-256 哈希值
     * @param input 原始字符串
     * @return 十六进制格式的哈希值
     */
    public static String sha256(String input) {
        if (input == null) {
            return null;
        }

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(input.getBytes());

            // 转换为十六进制字符串
            StringBuilder hexBuilder = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexBuilder.append('0');
                }
                hexBuilder.append(hex);
            }
            return hexBuilder.toString();
        } catch (NoSuchAlgorithmException e) {
            // SHA-256 是标准算法，不会抛出此异常
            throw new RuntimeException("未找到 SHA-256 算法", e);
        }
    }
}
